##    This file is part of The Most Awesome Story Ever
##
##    Foobar is free software: you can redistribute it and/or modify
##    it under the terms of the GNU General Public License as published by
##    the Free Software Foundation, either version 3 of the License, or
##    (at your option) any later version.
##
##    Foobar is distributed in the hope that it will be useful,
##    but WITHOUT ANY WARRANTY; without even the implied warranty of
##    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
##    GNU General Public License for more details.
##
##    You should have received a copy of the GNU General Public License
##    along with Foobar.  If not, see <http://www.gnu.org/licenses/>.
##    
##    Copyright 2008, Ryan Michela

import pagemodel
import images
import sgmllib
import string
from google.appengine.ext import db



def makePage(newPageOptionTitle, currentPageNum):
    """Create a new, empty record in the Pages database. Return the new
    page's page number as an int."""
        
    #get the largest current page number
    result = db.GqlQuery('SELECT * FROM Page ORDER BY pageNum DESC').fetch(1)
    lastPage = result[0]
    newPageNum = lastPage.pageNum + 1
    
    #add this option to the current page
    result = db.GqlQuery('SELECT * FROM Page WHERE pageNum = :1', 
                            int(currentPageNum))
    currentPage = result[0]
    currentPage.addOption(newPageOptionTitle, newPageNum)
    currentPage.put()
    
    #insert the new page into the database
    newPage = pagemodel.Page(pageNum = newPageNum)
    newPage.put()
    
    return newPageNum

def editPage(pageNum, pageTitle, pageBody, pageImage):
    """Fill a Page database record with content. Return any errors as a string,
    or None if no errors."""
    #sanity check the input
    if(pageTitle == ''):
        return 'Your new page must have a title. Name it somthing. Anything.'
    if(countWords(pageBody) < 100):
        return 'Your new page must be at least 100 words long. \
                Come on now. It''s not that hard!'
    
    #fetch the page to be edited
    result = db.GqlQuery('SELECT * FROM Page WHERE pageNum = :1', 
                            int(pageNum))
    currentPage = result[0]
    
    #update the record
    currentPage.title = pageTitle    
    validTags = ('p', 'strong', 'em', 'u', 'strike', 'sub', 'sup',
                    'ol', 'ul', 'li')
    currentPage.body = htmlStrip(pageBody, validTags)
    if(pageImage != ''):
        imageTouple = images.prepareImage(pageImage)
        currentPage.imageExtension = imageTouple[0]
        currentPage.image = db.Blob(imageTouple[1])
    
    #commit the record
    currentPage.put()
    
    return None

############################################################################

def countWords(text):
    """Return the number of whole words in a string as an int."""
    return len(htmlStrip(text).split(' '))
    
############################################################################
def htmlStrip(s, validTags = ()):
    """ Strip illegal HTML tags from string s """
    #http://code.activestate.com/recipes/52281/
    parser = StrippingParser()
    parser.valid_tags = validTags
    parser.feed(s)
    parser.close()
    parser.cleanup()
    return parser.result

class StrippingParser(sgmllib.SGMLParser):
    #http://code.activestate.com/recipes/52281/
    # These are the HTML tags that we will leave intact
    valid_tags = ()

    from htmlentitydefs import entitydefs # replace entitydefs from sgmllib
    
    def __init__(self):
        sgmllib.SGMLParser.__init__(self)
        self.result = ""
        self.endTagList = [] 
        
    def handle_data(self, data):
        if data:
            self.result = self.result + data

    def handle_charref(self, name):
        self.result = "%s&#%s;" % (self.result, name)
        
    def handle_entityref(self, name):
        if self.entitydefs.has_key(name): 
            x = ';'
        else:
            # this breaks unstandard entities that end with ';'
            x = ''
        self.result = "%s&%s%s" % (self.result, name, x)
    
    def unknown_starttag(self, tag, attrs):
        """ Delete all tags except for legal ones """
        if tag in self.valid_tags:       
            self.result = self.result + '<' + tag
            for k, v in attrs:
                if string.lower(k[0:2]) != 'on' and string.lower(v[0:10]) != 'javascript':
                    self.result = '%s %s="%s"' % (self.result, k, v)
            endTag = '</%s>' % tag
            self.endTagList.insert(0,endTag)    
            self.result = self.result + '>'
                
    def unknown_endtag(self, tag):
        if tag in self.valid_tags:
            self.result = "%s</%s>" % (self.result, tag)
            remTag = '</%s>' % tag
            self.endTagList.remove(remTag)

    def cleanup(self):
        """ Append missing closing tags """
        for j in range(len(self.endTagList)):
                self.result = self.result + self.endTagList[j]